/**
 * Express Web框架的应用模块
 * 1.导入所需模块
 * 2.导入路由模块
 * 3.应用层中间件
 * 4.定义路由
 * 5.导出Express应用实例
 */

//1.导入所需模块
//导入Express模块
var express = require('express');
//导入Node.js的路径模块
var path = require('path');
//导入Express的Cookie模块
var cookieParser = require('cookie-parser');
//导入日志模块
var logger = require('morgan');

//导入Session模块
const session=require("express-session");
//导入Session存储支持模块SQLite
const SQLiteStore=require("connect-sqlite3")(session);

//导入Swagger-ui-express模块
const swaggerUi=require("swagger-ui-express");
//导入Swagger-jsdoc模块
const swaggerJsdoc=require("swagger-jsdoc");
//导入初始化数据库中间件
const initSqliqteDB=require("./controller/init");

// 2.导入路由模块
//导入默认路由
var indexRouter = require('./routes/index');
//导入用户路由
var usersRouter = require('./routes/users');
//导入书籍路由
const booksRouter=require("./routes/books");
//导入书架路由
const bookshelfRouter=require("./routes/bookshelves");
//导入评论路由
const reviewRouter=require("./routes/reviews");

//生成应用实例"app"
var app = express();

// 3.应用层中间件
//开发日志
app.use(logger('dev'));
//JSON解析
app.use(express.json());
//URL编码
app.use(express.urlencoded({ extended: false }));
//Cookie
app.use(cookieParser());
//静态资源
app.use(express.static(path.join(__dirname, 'public')));

//中间件:Swagger
const options={
    definition:{
        openapi:"3.0.0",
        info:{
            title:"我的藏书馆接口",
            version:"1.0.0",
        },
    },
    apis:[path.join(__dirname,"./routes/*.js")],
};

const openapiSpecification=swaggerJsdoc(options);
app.use("/dev-api",swaggerUi.serve,swaggerUi.setup(openapiSpecification));

//中间件：数据库初始化
app.use(initSqliqteDB());

/**
 * Express中的Session支持
 * 1.npm install express-session connect-sqlite3
 * 2.导入模块
 * 3.使用Session中间件
 * 4.Session存储:SQLiteStore
 */

app.use(
    session({
    secret:"s$@dksksdfs122ddf",//session的salt
    resave:false,//session工作方式：session是否重新保存
    saveUninitialized:false,//session工作方式：未初始化的session是否保存
    cookie:{
        maxAge:7*24*60*60*1000,//sessionID在客户端cookie中保存1周
    },
    store:new SQLiteStore({
        db:"mylibrary.db",
        dir:"./data"
    })
}));

// 4.定义路由
//默认路由 -> /
app.use('/', indexRouter);
//用户路由 -> /users
app.use('/users', usersRouter);
//书籍路由 -> /books
app.use("/books",booksRouter);
//书架路由 -> /bookshelf
app.use("/bookshelves",bookshelfRouter);
//评论路由 -> /review
app.use("/reviews",reviewRouter);

// 5.导出Express应用实例
module.exports = app;